package com.bdcom.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bdcom.comp.ToolBarPanel;
import com.bdcom.model.BarrierType;
import com.bdcom.repository.BarrierTypeRepository;
import com.bdcom.util.PlannerUtil;

/**
 * 创建 线性障碍物 向导框
 * 
 * @author Guodeqi
 *
 */
@Component
public class BarrierTypeCfgDialog extends JDialog implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public JTable jtable = null;

	public DefaultTableModel dtm = null;

	List<BarrierType> typeList;

	private JButton newBtn;

	private JButton delBtn;

	private JButton saveBtn;

	private JButton freshBtn;
	@Autowired
	private BarrierTypeRepository barrierTypeRepository;

	public BarrierTypeCfgDialog() {

		setTitle(PlannerUtil.getString("barrierConfiguration"));

		setSize(300, 400);

		dtm = new DefaultTableModel(PlannerUtil.BARRIER_TAB_HEADER, 0);

		jtable = new JTable(dtm);

		MycellRenEdider renediter = new MycellRenEdider();

		jtable.getColumnModel().getColumn(2).setCellRenderer(renediter);

		jtable.getColumnModel().getColumn(2).setCellEditor(renediter);

		JScrollPane scrollpane = new JScrollPane(jtable);

		setLayout(new BorderLayout());

		add(scrollpane, BorderLayout.CENTER);

		JPanel panel = new JPanel();

		panel.add(newBtn = new JButton(PlannerUtil.getString("add")));

		newBtn.addActionListener(this);

		newBtn.setActionCommand("add");

		panel.add(delBtn = new JButton(PlannerUtil.getString("delete")));

		delBtn.addActionListener(this);

		delBtn.setActionCommand("del");

		panel.add(saveBtn = new JButton(PlannerUtil.getString("save")));

		saveBtn.addActionListener(this);

		saveBtn.setActionCommand("save");

		panel.add(freshBtn = new JButton(PlannerUtil.getString("refresh")));

		freshBtn.addActionListener(this);

		freshBtn.setActionCommand("refresh");

		add(panel, BorderLayout.SOUTH);

		setLocationRelativeTo(null);

		setResizable(false);

		setModal(true);

		setDefaultCloseOperation(HIDE_ON_CLOSE);

	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String command = e.getActionCommand();

		if ("add".equals(command)) {

			addRow();

		} else if ("del".equals(command)) {

			delRow();

		} else if ("save".equals(command)) {

			saveRow();

		} else if ("refresh".equals(command)) {

			loadTypes();
		}
	}

	private void saveRow() {
		// TODO Auto-generated method stub

		if (jtable.isEditing()) {
			
			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please finish editing"));
			
			return;
		}

		int row = jtable.getSelectedRow();

		if (row == -1) {

			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please choose one"));

			return;
		}

		if (dtm.getValueAt(row, 0).toString().equals("")) {
			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input texture"));
			return;
		}
		if (dtm.getValueAt(row, 1).toString().equals("")) {
			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input atternuation"));
			return;
		}

		BarrierType barrierType = new BarrierType();

		barrierType.setBarrierName(dtm.getValueAt(row, 0).toString().trim());

		int attenuation;

		try {

			attenuation = Integer.valueOf(dtm.getValueAt(row, 1).toString());

		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, PlannerUtil.getString("attenuation is not a number"));
			return;
		}

		barrierType.setAttenuation(attenuation);

		barrierType.setColor(dtm.getValueAt(row, 2).toString());

		barrierTypeRepository.save(barrierType);
		
		loadTypes();
	}

	private void delRow() {
		// TODO Auto-generated method stub
		int selected = jtable.getSelectedRow();

		if (selected == -1) {

			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please choose one"));

			return;
		}
		int result = JOptionPane.showConfirmDialog(null, PlannerUtil.getString("Yes or No"));

		if (result == JOptionPane.OK_OPTION) {
			/**
			 * 如果在设备类型model中存在，需要修改文件。
			 * 
			 * 若不存在，仅仅删除表中的数据。
			 * 
			 */

			if (selected < typeList.size()) {
				barrierTypeRepository.delete(typeList.get(selected));
				loadTypes();
			} else {
				dtm.removeRow(selected);
			}
		}
	}

	private void addRow() {
		// TODO Auto-generated method stub
		dtm.addRow(new Object[] { "", 0, "#000000" });

		jtable.setRowSelectionInterval(dtm.getRowCount() - 1, dtm.getRowCount() - 1);

	}

	private void removeTypes() {
		// TODO Auto-generated method stub
		int i = dtm.getRowCount() - 1;
		for (; i > -1; i--) {
			dtm.removeRow(i);
		}
		ToolBarPanel.barrierCombobox.removeAllItems();
	}

	@PostConstruct
	private void loadTypes() {
		// TODO Auto-generated method stub
		typeList = barrierTypeRepository.findAll();

		removeTypes();

		for (BarrierType barrierType : typeList) {
			dtm.addRow(new Object[] { barrierType.getBarrierName(), barrierType.getAttenuation(),
					barrierType.getColor() });
			ToolBarPanel.barrierCombobox.addItem(barrierType);
		}
	}

	class MycellRenEdider implements TableCellRenderer, TableCellEditor {

		JLabel label;

		public MycellRenEdider() {
			super();
			// TODO Auto-generated constructor stub
			label = new JLabel();
		}

		@Override
		public java.awt.Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
				boolean hasFocus, int row, int column) {
			// TODO Auto-generated method stub

			label.setText(value.toString());

			label.setBackground(Color.decode(value.toString()));

			label.setOpaque(true);

			return label;
		}

		@Override
		public Object getCellEditorValue() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public boolean isCellEditable(EventObject anEvent) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean stopCellEditing() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void cancelCellEditing() {
			// TODO Auto-generated method stub

		}

		@Override
		public void addCellEditorListener(CellEditorListener l) {
			// TODO Auto-generated method stub

		}

		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			// TODO Auto-generated method stub

		}

		@Override
		public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
				int column) {
			// TODO Auto-generated method stub

			Color color = JColorChooser.showDialog(null, PlannerUtil.getString("color"), Color.decode(value.toString()));

			if (color != null) {

				String R = Integer.toHexString(color.getRed());

				R = R.length() == 1 ? "0" + R : R;

				String G = Integer.toHexString(color.getGreen());

				G = G.length() == 1 ? "0" + G : G;

				String B = Integer.toHexString(color.getBlue());

				B = B.length() == 1 ? "0" + B : B;

				dtm.setValueAt("#" + R + G + B, row, column);

			}

			return null;
		}

	}

}
